//
//  CategoryViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/6/29.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//

#import "CategoryViewController.h"

@interface CategoryViewController ()

@end

@implementation CategoryViewController

@synthesize level;
@synthesize parentCode;
@synthesize currentCode;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.delegate = self;
        level = 0;
        parentCode = RichCategoryCodeRoot;
        currentCode = RichCategoryCodeRoot;
        modifiedCategories = [[NSMutableDictionary alloc] init];
        self.rowsNotAllowEditing = 3;
        
        self.tableView.tag = RichTableViewTagCategory;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    [self.tableView setAllowsSelectionDuringEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backToUpperLevel)
                                                 name:@"CategoryNotificationBackToUpperLevel"
                                               object:nil];
    
    [[RichDelegate core] loadCategories];
    
    if (level > 0) {
        NSString *_categoryName = [[RichDelegate core] findCategoryByCode:parentCode];
        self.title = _categoryName;
    }
    else
        self.title = RichLocaleString(@"Category Setting");
    
    [self.tableView reloadData];
    
    [self updateNavigationBarItems];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CategoryNotificationBackToUpperLevel" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    if (editing && self.mode == RichTableModeListEditable)
        self.mode = RichTableModeUpdate;
    else
        self.mode = RichTableModeListEditable;
    
    [super setEditing:editing animated:animated];
    
    [self updateNavigationBarItems];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.mode == RichTableModeCreate)
        return 1;
    else
        return [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (self.mode == RichTableModeListReadonly) {
        tableCellStyle = RichTableCellStyleDefault;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        NSArray *keys = [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] allKeys];
        NSNumber *key = [[keys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[indexPath row]];
        NSString *name = [[[RichDelegate core] category] objectForKey:key];
        
        if ([[[[RichDelegate core] categoriesAtLevel:level + 1 parentCode:[key intValue]] allKeys] count] > 0) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        if (name) {
            cell.textLabel.text = name;
        }
    }
    else if (self.mode == RichTableModeListEditable || self.mode == RichTableModeUpdate) {
        NSArray *keys = [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] allKeys];
        NSNumber *key = [[keys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[indexPath row]];
        NSString *name = [[[RichDelegate core] category] objectForKey:key];
        
        if (self.isEditing) {
            tableCellStyle = RichTableCellStyleTextfield;
            RichTableViewTextfieldCell *textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
            
            cell = textfieldCell;
            
            if (level == 0 && [indexPath row] < 3) {
                textfieldCell.userInteractionEnabled = NO;
                textfieldCell.textfield.textColor = [UIColor grayColor];
            }
            else {
                textfieldCell.userInteractionEnabled = YES;
                textfieldCell.textfield.textColor = [UIColor blackColor];
            }
            
            textfieldCell.textLabel.text = @"";
            textfieldCell.textfield.text = name;
            textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
        }
        else {
            tableCellStyle = RichTableCellStyleDefault;
            cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.textLabel.text = name;
            
            if (level < 3)
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    else {
        tableCellStyle = RichTableCellStyleTextfield;
        RichTableViewTextfieldCell *textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        cell = textfieldCell;
        
        textfieldCell.textLabel.text = RichLocaleString(@"Name");
        textfieldCell.textfield.placeholder = RichLocaleString(@"Category Name");
        textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
        
        
    }
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.mode == RichTableModeListEditable || self.mode == RichTableModeUpdate) {
        if (level == 0 && [indexPath row] < 3)
            return NO;
        else
            return YES;
    }
    else
        return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger minCount = 0;
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSArray *keys = [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] allKeys];
        NSNumber *key = [[keys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[indexPath row]];
        [[RichDelegate core] deleteCategory:[key intValue]];
        
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        if (level == 0)
            minCount = 3;
        
        if (self.mode == RichTableModeUpdate) {
            if ([keys count] - 1 == minCount) {
                self.navigationItem.rightBarButtonItem = nil;
                [self setEditing:NO];
            }
            else {
                if (self.isEditing)
                    self.navigationItem.rightBarButtonItem = self.barDoneButtonItem;
                else
                    self.navigationItem.rightBarButtonItem = self.barEditButtonItem;
            }
        }
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isEditing)
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleNone;
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    if (self.mode == RichTableModeListReadonly) {
        if ([indexPath section] == 0) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            
            if ([tableView isEditing])
                return;
            
            NSArray *keys = [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] allKeys];
            NSNumber *key = [[keys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[indexPath row]];
            
            if ([[[[RichDelegate core] categoriesAtLevel:level + 1 parentCode:[key intValue]] allKeys] count] > 0) {
                ++level;
                self.parentCode = [key intValue];
                
                [self.tableView reloadData];
            }
            else {
                currentCode = [key intValue];
                [self.callerDelegate tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath];
            }
        }
        
        return;
    }
    else if (self.mode == RichTableModeListEditable) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        if ([tableView isEditing])
            return;
        
        if (level < 3) {
            NSArray *keys = [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] allKeys];
            NSNumber *key = [[keys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[indexPath row]];
            CategoryViewController *cvc = [[CategoryViewController alloc] initWithStyle:UITableViewStylePlain];
            
            cvc.navigator = self.navigator;
            cvc.level = level + 1;
            cvc.parentCode = [key intValue];
            
            [self.navigator pushViewController:cvc animated:YES];
            [cvc release];
        }
    }
}

#pragma mark - Navigation bar item update

- (void)updateNavigationBarItems
{
    if (self.mode == RichTableModeListEditable || self.mode == RichTableModeUpdate) {
        if ((level == 0 && [self tableView:self.tableView numberOfRowsInSection:0] > 3) ||
            (level > 0 && [self tableView:self.tableView numberOfRowsInSection:0] > 0)) {
            if (self.isEditing)
                self.navigationItem.rightBarButtonItem = self.barDoneButtonItem;
            else
                self.navigationItem.rightBarButtonItem = self.barEditButtonItem;
        }
        else
            self.navigationItem.rightBarButtonItem = nil;
    }
}

#pragma mark - Textfield delegate

- (void)textFieldDidChange:(UITextField *)textField
{
    [super textFieldDidChange:textField];

    if (textField.tag >= 0) {
        NSArray *keys = [[[RichDelegate core] categoriesAtLevel:level parentCode:parentCode] allKeys];
        if ([keys count]) {
            NSNumber *key = [[keys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:textField.tag];
            [modifiedCategories setObject:textField.text forKey:key];
        }
    }
}

#pragma mark - Notification handler

- (void)backToUpperLevel
{
    if (level > 1) {
        --level;
        parentCode = [[RichDelegate core] parentCodeOf:parentCode atLevel:level];

        [self.tableView reloadData];
    }
}

#pragma mark - RichTableViewController Delegate

- (void)didPressCreate
{
    CategoryViewController *cvc = [[CategoryViewController alloc] initWithStyle:UITableViewStylePlain];
    cvc.navigator = self.navigator;
    cvc.mode = RichTableModeCreate;
    cvc.level = level;
    cvc.parentCode = parentCode;
    [self.navigator pushViewController:cvc animated:YES];
    [cvc release];
}

- (void)didPressCreateDone
{
    NSInteger newId = [[RichDelegate core] nextCategoryIdAtLevel:level parentCode:parentCode];
    NSUInteger newCode = parentCode | ((newId & 0xff) << (level * 8));
    
    if (currentTextfield == nil || [currentTextfield.text isEqualToString:@""]) {
        NSLog(@"Empty category name");
    }
    else {
        if ([[RichDelegate core] createCategory:newCode name:currentTextfield.text] != RICH_OK)
            NSLog(@"Create category failed");
    }
    
    [self.navigator popViewControllerAnimated:YES];
}

- (void)didPressUpdateDone
{
    for (NSNumber *key in [modifiedCategories allKeys]) {
        [[RichDelegate core] updateCategory:[key intValue] name:[modifiedCategories objectForKey:key]];
    }
    
    [modifiedCategories removeAllObjects];
    
    [self setEditing:NO animated:YES];
}

@end
